package com.itheima.service.impl;

import com.itheima.dao.RouteDao;
import com.itheima.domain.PageBean;
import com.itheima.domain.Route;
import com.itheima.service.RouteService;
import com.itheima.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RouteServiceImpl implements RouteService {


    @Override
    public PageBean<Route> findByPage(int currentPage, int pageSize, String cid) {
        // 创建dao代理对象
        SqlSession sqlSession = MyBatisUtils.openSession();
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        // 1.创建PageBean
        PageBean<Route> pageBean = new PageBean<>();
      /*  // 2.封装当前页和每页个数
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        // 3.调用dao查询总记录数，封装
        Integer totalCount = routeDao.findCount(cid, rname);
        pageBean.setTotalCount(totalCount);
        // 4.计算总页数，封装
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        pageBean.setTotalPage(totalPage);
        // 5.计算开始索引
        int index = (currentPage - 1) * pageSize;
        // 6.调用dao查询结果集，封装
        List<Route> routeList = routeDao.findList(index, pageSize, cid, rname);
        pageBean.setList(routeList);

        // 释放资源
        MyBatisUtils.close(sqlSession);*/
        // 7.返回分页对象
        return pageBean;
    }

    @Override
    public PageBean<Route> findByPage(int currentPage, int pageSize, String cid,String rname) {
        // 创建dao代理对象
        SqlSession sqlSession = MyBatisUtils.openSession();
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        // 1.创建PageBean
        PageBean<Route> pageBean = new PageBean<>();
        // 2.封装当前页和每页个数
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        // 3.调用dao查询总记录数，封装
        Integer totalCount = routeDao.findCount(cid,rname);
        pageBean.setTotalCount(totalCount);
        // 4.计算总页数，封装
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        pageBean.setTotalPage(totalPage);
        // 5.计算开始索引
        int index = (currentPage - 1) * pageSize;
        // 6.调用dao查询结果集，封装
        List<Route> routeList = routeDao.findList(index, pageSize, cid,rname);
        pageBean.setList(routeList);

        // 释放资源
        MyBatisUtils.close(sqlSession);
        // 7.返回分页对象
        return pageBean;
    }

    @Override
    public Route findDetail(String rid) {
        //创建dao代理
        SqlSession sqlSession = MyBatisUtils.openSession();
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);
        //调用dao
        Route route=routeDao.findByRidWithAll(rid);
        //释放资源
        MyBatisUtils.close(sqlSession);
        return route;
    }

    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);
        System.out.println(routeDao);

    }
}
